import tinymce from 'tinymce/tinymce'
import { v4 as uuid } from 'uuid'
import { getNumber, openResetNumberDialog, classMatch, resetNotesSiblingsNumber } from '@/utils/exampleTag'
import { checkBeforeInsert } from '@/utils/helpers'
import { resetItemListSiblingsNumber } from '../itemlist/itemlistSetting'
import { insertElementAfterBlock } from '@/utils/dom'
import { Message } from 'element-ui'

tinymce.PluginManager.add('example', function (editor) {
  editor.on('keydown', (event) => {
    if ('Backspace' === event.key) {
      // 在示例、条文注、列项的最后一个空行按删除，此时当前行的示例变成段落，光标停留在当前行
      const node = editor.selection.getNode()
      const content = node.textContent.replace(/[\u200B-\u200D\uFEFF]/g, '')
      if (content?.length > 0) return
      const monitorClassList = ['example', 'item_note']
      const flag = monitorClassList.some((className) => node?.classList.contains(className))
      // 列项因为不可以被打断，故只有最后一个才可以删除编号，中间的列项不可以删除编号
      const next = node.nextElementSibling
      const bulletFlag = node?.classList.contains('item_list') &&
        (!next ||
          (next && (!next.classList.contains('item_list') || node.dataset.lang !== next.dataset.lang))
        )
      if (flag || bulletFlag) {
        const dataLang = node.dataset.lang
        const className = node.className
        console.log('example --- keydown--- Backspace---check deletedNode')
        event.preventDefault()
        event.stopPropagation()
        editor.dom.removeAllAttribs(node)
        editor.dom.setAttribs(node, {
          'class': '',
          'data-type': 'paragraph',
          'data-id': uuid(),
          'data-block-id': uuid(),
          'data-lang': dataLang
        })
        if (className.includes('item_list')) {
          resetItemListSiblingsNumber(node, editor, dataLang)
        } else {
          resetNotesSiblingsNumber({ node, editor, classList: monitorClassList, dataLang })
        }
        editor.selection.setCursorLocation(node, 0)
        return false
      }
    }
  })

  editor.on('keyup', (event) => {
    const node = editor.selection.getNode()
    const prevNode = node?.previousSibling
    const _classMatch = classMatch(prevNode?.className || '', ["example", "item_note"])
    if (!_classMatch) return
    if ("Enter" === event.key && prevNode.dataset?.number) {
      console.log('---PluginManager example keyup---')
      // 从示例x所在行按住enter，下一行示例x的编号+1
      const number = getNumber({
        node,
        classList: ['example', 'item_note'],
        dataLang: prevNode.dataset.lang
      })
      editor.dom.setAttribs(node, {
        'class': prevNode.className,
        'data-number': number,
        'data-id': uuid(),
        'data-block-id': uuid(),
        'data-share-id': uuid(),
        'data-lang': prevNode.dataset.lang,
        'data-type': prevNode.dataset.type
      })
      resetNotesSiblingsNumber({ node, editor, classList: [prevNode.dataset.type], dataLang: prevNode.dataset.lang })
    }

    if (event.key === 'Delete') {
      // 删除了当前行，重置后面的编号
      const prev = node.previousElementSibling
      const prevClassName = prev?.getAttribute('class') || ''
      const _classMatch = classMatch(prevClassName, ['example', 'item_note'])
      const prevResetFlag = prev && prev.nodeName === node.nodeName && _classMatch && !node.dataset.restart ? true : false

      if (prevResetFlag) {
        resetNotesSiblingsNumber({ node, editor, classList: [node.dataset.type], dataLang: node.dataset.lang})
      }
    }
    if (event.key === 'Delete' || event.key === 'Backspace') {
      // 删除了下一行，重置后面的连续编号
      const next = node.nextElementSibling
      const className = next?.getAttribute('class') || ''
      const match = classMatch(className, ['example', 'item_note'])
      const nextResetFlag = next && next.nodeName === node.nodeName && match && !node.dataset.restart ? true : false

      if (nextResetFlag) {
        resetNotesSiblingsNumber({ node, editor, classList: [node.dataset.type], dataLang: node.dataset.lang})
      }
    }
  })

  // 添加命令
  editor.addCommand('toggleExample', (ui, value) => {
    const { action, numbered, dataLang } = value
    const node = editor.selection.getNode()
    if (node.dataset.type === 'table' || editor.dom.getParent(node, 'table')) {
      return Message.warning({
        message: `表格中暂不支持插入${action === 'example' ? '示例' : '注'}`,
        showClose: true
      })
    }
    if (editor.dom.getParent(node, 'div[data-type="figure"]')) {
      return Message.warning({
        message: `图结构化中暂不支持插入${action === 'example' ? '示例' : '注'}`,
        showClose: true
      })
    }
    if (node.dataset?.type === 'item_list' || editor.dom.getParent(node, 'p.item_list')) {
      return Message.warning({
        message: `列项中暂不支持插入${action === 'example' ? '示例' : '注'}`,
        showClose: true
      })
    }
    // 新起一行插入
    let number = 1
    let config = {
      'data-type': action,
      'data-id': uuid(),
      'data-share-id': uuid(),
      'data-block-id': uuid(),
      'class': `${action} ${dataLang}`,
      'data-lang': dataLang
    }
    if (numbered) {
      const _classMatch = classMatch(node.className, [action])
      if (_classMatch && node.dataset.number) {
        number = parseInt(node.dataset.number) + 1
      }
      config['data-number'] = number
    }
    const currentContent = node.textContent.replace(/[\u200B-\u200D\uFEFF]/g, "")
    if (node.dataset.type === 'paragraph' && currentContent?.length === 0) {
      // 如果当前行是空的段落，就将当前行作为示例或注
      editor.dom.removeAllAttribs(node)
      editor.dom.setAttribs(node, config)
    } else {
      const content = editor.dom.create('p', config, '<br>')
      insertElementAfterBlock(content, editor)
      editor.selection.setCursorLocation(content, 0)
    }
    // 需要将后面的连续示例编号重置
    if (numbered) {
      resetNotesSiblingsNumber({ node, editor, classList: [action], dataLang })
    }
  })

  // 将选中的节点(目前只处理段落、列项)变成示例内容，优先使用示例的字体字号
  editor.addCommand('toggleExampleContent', (ui, value) => {
    const node = editor.selection.getNode()
    const classList = node.classList || []
    if (classList?.contains('page_body')) {
      // 选择了多行数据
      const firstNode = editor.selection.getStart()
      const lastNode = editor.selection.getEnd()
      const isExample = firstNode.dataset.isExample === '1' ? false : true
      const walk = (node, last) => {
        toggleExampleContent(node, isExample)
        if (node?.dataset?.id !== last.dataset.id) {
          walk(node.nextElementSibling, last)
        }
      }
      walk(firstNode, lastNode)
    } else {
      let parent = editor.dom.getParent(node, 'p[data-type="paragraph"]')
      if (parent) {
        return toggleExampleContent(parent, parent.dataset.isExample === '1' ? false : true)
      }
      parent = editor.dom.getParent(node, 'p[data-type="item_list"]')
      if (parent) {
        return toggleExampleContent(parent, parent.dataset.isExample === '1' ? false : true)
      }
      return toggleExampleContent(node, node.dataset.isExample === '1' ? false : true)
    }
  })
  function toggleExampleContent (node, isExample=true) {
    // 目前只特殊处理列项、段落为示例内容
    if (['paragraph', 'item_list'].some(i => node.dataset.type === i)) {
      if (isExample) {
        editor.dom.setAttribs(node, {
          'data-is-example': 1
        })
      } else {
        node.removeAttribute('data-is-example')
      }
    }
  }

  const icon = `
    <svg width="24px" height="25px" viewBox="0 0 24 25" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g transform="translate(-1310.000000, -161.000000)" fill="#000000" fill-rule="nonzero"> <g id="tool" transform="translate(16.000000, 149.500000)"> <g id="编组-2" transform="translate(190.000000, 8.000000)"> <g id="示例" transform="translate(1104.000000, 3.500000)"> <rect id="矩形" opacity="0" x="0" y="0.5" width="24" height="24"></rect> <path d="M22,3.85714286 C22.5522847,3.85714286 23,4.30485811 23,4.85714286 L23,20.1428571 C23,20.6951419 22.5522847,21.1428571 22,21.1428571 L2,21.1428571 C1.44771525,21.1428571 1,20.6951419 1,20.1428571 L1,4.85714286 C1,4.30485811 1.44771525,3.85714286 2,3.85714286 L22,3.85714286 Z M21.3,5.557 L2.7,5.557 L2.7,19.442 L21.3,19.442 L21.3,5.557 Z" id="矩形"></path> <path d="M3.45703125,12.2051626 L3.45703125,11.2911001 L11.6132812,11.2911001 L11.6132812,12.2051626 L8.34375,12.2051626 L8.34375,15.2989126 C8.3671875,16.2364126 7.8984375,16.6934438 6.9375,16.6700063 L5.8125,16.6700063 L5.8125,15.8262563 L6.33984375,15.8262563 C6.73828125,15.8496938 6.92578125,15.6621938 6.90234375,15.2637563 L6.90234375,12.2051626 L3.45703125,12.2051626 Z M4.1953125,9.99031883 L4.1953125,9.07625633 L10.9101562,9.07625633 L10.9101562,9.99031883 L4.1953125,9.99031883 Z M3.45703125,15.9317251 L3.45703125,15.1582876 C4.23046875,14.6661001 4.7109375,13.9395376 4.8984375,12.9786001 L6.234375,12.9786001 C5.8828125,14.5489126 4.95703125,15.5332876 3.45703125,15.9317251 Z M11.578125,15.9317251 C10.125,15.5332876 9.234375,14.5489126 8.90625,12.9786001 L10.2421875,12.9786001 C10.4296875,13.9864126 10.875,14.7129751 11.578125,15.1582876 L11.578125,15.9317251 Z" id="形状"></path> <path d="M14.7421875,9.88485008 L14.7421875,9.07625633 L17.6601562,9.07625633 L17.6601562,9.88485008 L16.2539062,9.88485008 C16.2304688,10.1895376 16.1953125,10.4825063 16.1484375,10.7637563 L17.5195312,10.7637563 L17.5195312,11.5723501 C17.4726562,13.9395376 16.5117188,15.7090688 14.6367188,16.8809438 L14.6367188,15.9317251 C15.2460938,15.2754751 15.703125,14.5840688 16.0078125,13.8575063 C15.703125,13.6700063 15.3867188,13.5411001 15.0585938,13.4707876 L15.0585938,12.8731313 C14.8945312,13.0137563 14.7070312,13.1661001 14.4960938,13.3301626 L14.4960938,12.3457876 C14.9179688,11.7364126 15.1523438,10.9161001 15.1992188,9.88485008 L14.7421875,9.88485008 Z M13.0546875,16.8106313 L13.0546875,11.9590688 C12.84375,12.0996938 12.609375,12.2168813 12.3515625,12.3106313 L12.3515625,11.5020376 C12.9609375,10.9864126 13.3476562,10.0723501 13.5117188,8.75985008 L14.671875,8.75985008 C14.5546875,9.50985008 14.390625,10.1309438 14.1796875,10.6231313 L14.1796875,16.8106313 L13.0546875,16.8106313 Z M18.1875,16.6700063 L18.1875,15.8614126 L18.8203125,15.8614126 C19.1015625,15.8614126 19.2421875,15.7207876 19.2421875,15.4395376 L19.2421875,8.72469383 L20.3320312,8.72469383 L20.3320312,15.5801626 C20.3554688,16.3301626 19.9804688,16.6934438 19.2070312,16.6700063 L18.1875,16.6700063 Z M17.8710938,14.9121938 L17.8710938,9.60360008 L18.8203125,9.60360008 L18.8203125,14.9121938 L17.8710938,14.9121938 Z M16.5,11.5723501 L15.9023438,11.5723501 C15.7148438,12.0176626 15.5039062,12.3575063 15.2695312,12.5918813 C15.6445312,12.6621938 15.984375,12.7442251 16.2890625,12.8379751 C16.359375,12.4864126 16.4296875,12.0645376 16.5,11.5723501 Z" id="形状"></path> </g> </g> </g> </g> </g> </svg>
  `
  editor.ui.registry.addIcon('exampleIcon', icon);
  return (
    editor.ui.registry.addMenuButton('example', {
      tooltip: '示例',
      icon: 'exampleIcon',
      fetch: function (callback) {
        callback([
          {
            type: 'menuitem',
            text: '示例',
            onAction: function () {
              if (!checkBeforeInsert('example')) return
              editor.execCommand('toggleExample', false, { action: 'example', dataLang: 'zh' })
            }
          },
          {
            type: 'menuitem',
            text: '示例X',
            onAction: function () {
              if (!checkBeforeInsert('example')) return
              editor.execCommand('toggleExample', false, { action: 'example', numbered: true, dataLang: 'zh' })
            }
          },
          {
            type: 'menuitem',
            text: '重新编号',
            onAction: function () {
              if (!checkBeforeInsert('example')) return
              openResetNumberDialog(editor, 'example')
            }
          },
          {
            type: 'menuitem',
            text: '示例内容',
            onAction: function () {
              if (!checkBeforeInsert('example')) return
              editor.execCommand('toggleExampleContent', false, {})
            }
          }
        ])
      }
    }),
    {
      getMetadata: function () {
        return {
          name: '示例',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})
